﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FastPoster.MainForms
{
    #region using
    using DevComponents.DotNetBar;
    using FastPoster.DataProviders.BUS;
    using FastPoster.DataProviders.DTO;
    using FastPoster.Helpers;
    using System.IO;
    using System.Text.RegularExpressions;
    #endregion

    public partial class FrmDienDan : Office2007Form
    {
        public DataSet          DSDanhMuc { get; set; }
        private int             SelectedDienDan = -1;
        private EnumUpdateMode  UpdateMode = EnumUpdateMode.NONE;
        private string          FileName;

        public FrmDienDan()
        {
            InitializeComponent();
            InitGridViewBoxLinks();
            InitGridViewDanhSachDienDan();
        }

        private void FrmDienDan_Load(object sender, EventArgs e)
        {
            LoadBoxLinks();
            LoadDanhSachDienDan();
        }

        public void ClearSelection()
        {
            dtgvDanhSachDienDan.ClearSelection();
            dtgvBoxLinks.ClearSelection();
        }

        public void ResetForm()
        {
            txtLinkDienDan.Text = string.Empty;
            txtTenDangNhap.Text = string.Empty;
            txtMatKhau.Text = string.Empty;
            SelectedDienDan = -1;
            foreach (DataGridViewRow row in dtgvBoxLinks.Rows)
            {
                row.Cells["ID"].Value = string.Empty;
                row.Cells["URL"].Value = string.Empty;
            }
        }

        private void btnNhapMoi_Click(object sender, EventArgs e)
        {
            ResetForm();
        }

        private void InitGridViewBoxLinks()
        {
            DataGridViewTextBoxColumn objColumn = new DataGridViewTextBoxColumn
            {
                Visible = false,
                HeaderText = "ID",
                DataPropertyName = "ID",
                Name = "ID"
            };
            dtgvBoxLinks.Columns.Add(objColumn);

            objColumn = new DataGridViewTextBoxColumn
            {
                Visible = false,
                HeaderText = "IDDanhMuc",
                DataPropertyName = "IDDanhMuc",
                Name = "IDDanhMuc"
            };
            dtgvBoxLinks.Columns.Add(objColumn);

            objColumn = new DataGridViewTextBoxColumn
            {
                HeaderText = "Danh mục",
                DataPropertyName = "TenDanhMuc",
                Name = "TenDanhMuc",
                Width = (int)((dtgvBoxLinks.Width - dtgvBoxLinks.RowHeadersWidth) * ((double)1 / 3)) - 1
            };
            dtgvBoxLinks.Columns.Add(objColumn);

            objColumn = new DataGridViewTextBoxColumn
            {
                HeaderText = "Box links",
                DataPropertyName = "URL",
                Name = "URL",
                Width = (int)((dtgvBoxLinks.Width - dtgvBoxLinks.RowHeadersWidth) * ((double)2 / 3)) - 1
            };
            dtgvBoxLinks.Columns.Add(objColumn);
        }

        public void LoadBoxLinks()
        {
            var objBUS = new DanhMucBUS(GlobalVariables.g_strPath);
            DSDanhMuc = objBUS.SelectAll();

            var dt = new DataTable();
            dt.Columns.Add("ID");
            dt.Columns.Add("IDDanhMuc");
            dt.Columns.Add("TenDanhMuc");
            dt.Columns.Add("URL");

            for (int i = 0; i < DSDanhMuc.Tables[0].Rows.Count; i++)
            {
                var row = DSDanhMuc.Tables[0].Rows[i];
                var objBoxBus = new BoxBUS(GlobalVariables.g_strPath);
                //var ds = objBoxBus.SelectByDienDanAnhDanhMuc(
                dt.Rows.Add(string.Empty, row["ID"].ToString(), row["TenDanhMuc"].ToString(), string.Empty);
            }

            DataView objTimeSheetDV = new System.Data.DataView(dt);
            objTimeSheetDV.AllowNew = false;
            dtgvBoxLinks.AutoGenerateColumns = false;
            dtgvBoxLinks.DataSource = objTimeSheetDV;
        }

        private void InitGridViewDanhSachDienDan()
        {
            DataGridViewTextBoxColumn objColumn = new DataGridViewTextBoxColumn
            {
                Visible = false,
                HeaderText = "ID",
                DataPropertyName = "ID",
                Name = "ID"
            };
            dtgvDanhSachDienDan.Columns.Add(objColumn);

            objColumn = new DataGridViewTextBoxColumn
            {
                HeaderText = "STT",
                DataPropertyName = "STT",
                Name = "STT",
                Width = (int)((dtgvDanhSachDienDan.Width - dtgvDanhSachDienDan.RowHeadersWidth) * ((double)1 / 7)) - 1
            };
            dtgvDanhSachDienDan.Columns.Add(objColumn);

            objColumn = new DataGridViewTextBoxColumn
            {
                HeaderText = "Link diễn đàn",
                DataPropertyName = "URL",
                Name = "URL",
                Width = (int)((dtgvDanhSachDienDan.Width - dtgvDanhSachDienDan.RowHeadersWidth) * ((double)6 / 7)) - 1
            };
            dtgvDanhSachDienDan.Columns.Add(objColumn);
        }

        public void LoadDanhSachDienDan()
        {
            var objBUS = new DienDanBUS(GlobalVariables.g_strPath);
            var ds = objBUS.SelectAll();

            var dt = new DataTable();
            dt.Columns.Add("ID");
            dt.Columns.Add("STT");
            dt.Columns.Add("URL");

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                var row = ds.Tables[0].Rows[i];
                dt.Rows.Add(row["ID"].ToString(), (i + 1).ToString(), row["URL"].ToString());
            }

            DataView objTimeSheetDV = new System.Data.DataView(dt);
            objTimeSheetDV.AllowNew = false;
            dtgvDanhSachDienDan.AutoGenerateColumns = false;
            dtgvDanhSachDienDan.DataSource = objTimeSheetDV;
        }

        public bool CheckingDienDanIsValid(string url)
        {
            string pattern = @"(ftp|http):\/\/([_a-z\d\-]+(\.[_a-z\d\-]+)+)";
            Regex urlregex = new Regex(pattern);
            Match m = urlregex.Match(url);
            // Valid URL
            if (m.Success)
            {
                return true;
            }
            return false;
        }

        public bool CheckingDienDanIsExist(string url)
        {
            // Search duplicate urls
            for (int i = 0; i < dtgvDanhSachDienDan.Rows.Count; i++)
            {
                var first1 = dtgvDanhSachDienDan.Rows[i].Cells["URL"].Value.ToString().IndexOf("www.");
                var last1 = -1;
                var p1 = "";
                if (first1 == -1)
                {
                    first1 = dtgvDanhSachDienDan.Rows[i].Cells["URL"].Value.ToString().IndexOf("//");
                    last1 = dtgvDanhSachDienDan.Rows[i].Cells["URL"].Value.ToString().IndexOf("/", first1 + 2);
                    if (last1 == -1)
                    {
                        last1 = dtgvDanhSachDienDan.Rows[i].Cells["URL"].Value.ToString().Length;
                    }
                    // Get pattern 2
                    p1 = dtgvDanhSachDienDan.Rows[i].Cells["URL"].Value.ToString().Substring(first1 + 2, last1 - first1 - 2);
                }
                else
                {
                    last1 = dtgvDanhSachDienDan.Rows[i].Cells["URL"].Value.ToString().IndexOf("/", first1 + 4);
                    if (last1 == -1)
                    {
                        last1 = dtgvDanhSachDienDan.Rows[i].Cells["URL"].Value.ToString().ToString().Length;
                    }
                    // Get pattern 2
                    p1 = dtgvDanhSachDienDan.Rows[i].Cells["URL"].Value.ToString().Substring(first1 + 4, last1 - first1 - 4);
                }

                ///////////////////////////////////////////////////

                var first2 = url.IndexOf("www.");
                var last2 = -1;
                var p2 = "";
                if (first2 == -1)
                {
                    first2 = url.IndexOf("//");
                    last2 = url.IndexOf("/", first2 + 2);
                    if (last2 == -1)
                    {
                        last2 = url.ToString().Length;
                    }
                    // Get pattern 2
                    p2 = url.Substring(first2 + 2, last2 - first2 - 2);
                }
                else
                {
                    last2 = url.IndexOf("/", first2 + 4);
                    if (last2 == -1)
                    {
                        last2 = url.ToString().Length;
                    }
                    // Get pattern 2
                    p2 = url.Substring(first2 + 4, last2 - first2 - 4);
                }
                
                if (p1.Trim().ToUpper() == p2.Trim().ToUpper())
                {
                    return true;
                }
            }
            return false;
        }

        public bool ValidateInput(ref string errText)
        {
            if (txtLinkDienDan.Text.Trim() == string.Empty)
            {
                errText = "Vui lòng nhập link diễn đàn";
                return false;
            }
            if (!CheckingDienDanIsValid(txtLinkDienDan.Text.Trim()))
            {
                errText = "Link diễn đàn không đúng định dạng hợp lệ";
                return false;
            }
            return true;
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            try
            {
                string errText = string.Empty;
                if (SelectedDienDan != -1)
                {
                    MessageBoxEx.Show("Hiện thời đang chọn 1 diễn đàn nên không thể thêm mới được", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (!ValidateInput(ref errText))
                {
                    MessageBoxEx.Show(errText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (CheckingDienDanIsExist(txtLinkDienDan.Text.Trim()))
                {
                    MessageBoxEx.Show("Diễn đàn đã tồn tại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                UpdateMode = EnumUpdateMode.INSERT;
                // Insert DienDan
                var objDienDanBus = new DienDanBUS(GlobalVariables.g_strPath);
                var objDienDanDto = new DienDanDTO
                {
                    URL = txtLinkDienDan.Text.Trim(),
                    TenDangNhap = txtTenDangNhap.Text.Trim(),
                    MatKhau = txtMatKhau.Text.Trim()
                };
                if (objDienDanBus.Insert(objDienDanDto))
                {
                    // Select max id -> that mean select id of DienDan just inserted
                    objDienDanBus = new DienDanBUS(GlobalVariables.g_strPath);
                    var maxID = objDienDanBus.RetrieveMaxID().Tables[0].Rows[0][0].ToString();

                    // Loop for list of Box
                    foreach (DataGridViewRow row in dtgvBoxLinks.Rows)
                    {
                        if (row.Cells["URL"].Value.ToString() != string.Empty)
                        {
                            var objBoxBux = new BoxBUS(GlobalVariables.g_strPath);
                            var objBoxDto = new BoxDTO
                            {
                                IDDienDan = int.Parse(maxID),
                                IDDanhMuc = int.Parse(row.Cells["ID"].Value.ToString()),
                                URL = row.Cells["URL"].Value.ToString()
                            };
                            objBoxBux.Insert(objBoxDto);
                        }
                    }
                    // Reload danh sach dien dan
                    LoadDanhSachDienDan();
                    SelectedDienDan = int.Parse(maxID);
                    MessageBoxEx.Show("Thêm dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                UpdateMode = EnumUpdateMode.NONE;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex.InnerException);
            }
        }

        private void dtgvDanhSachDienDan_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (dtgvDanhSachDienDan.SelectedRows == null || dtgvDanhSachDienDan.SelectedRows.Count == 0)
                    return;
                var selectedItem = dtgvDanhSachDienDan.SelectedRows[0];
                SelectedDienDan = int.Parse(dtgvDanhSachDienDan.SelectedRows[0].Cells["ID"].Value.ToString());

                var objBUS = new DienDanBUS(GlobalVariables.g_strPath);
                var ds = objBUS.SelectByID(SelectedDienDan);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    var row = ds.Tables[0].Rows[0];
                    LoadDienDanInfo(row);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex.InnerException);
            }
        }

        public void LoadDienDanInfo(DataRow datarow)
        {
            txtLinkDienDan.Text = datarow["URL"].ToString();
            txtTenDangNhap.Text = datarow["TenDangNhap"].ToString();
            txtMatKhau.Text = datarow["MatKhau"].ToString();

            // Load box list
            foreach (DataGridViewRow row in dtgvBoxLinks.Rows)
            {
                var idDanhMuc = int.Parse(row.Cells["IDDanhMuc"].Value.ToString());
                var objBoxBus = new BoxBUS(GlobalVariables.g_strPath);
                var ds = objBoxBus.SelectByDienDanAnhDanhMuc(SelectedDienDan, idDanhMuc);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    row.Cells["ID"].Value = ds.Tables[0].Rows[0]["ID"].ToString();
                    row.Cells["URL"].Value = ds.Tables[0].Rows[0]["URL"].ToString();
                }
                else
                {
                    row.Cells["ID"].Value = string.Empty;
                    row.Cells["URL"].Value = string.Empty;
                }
            }
        }

        private void btnCapNhat_Click(object sender, EventArgs e)
        {
            try
            {
                string errText = string.Empty;
                if (SelectedDienDan == -1)
                {
                    MessageBoxEx.Show("Vui lòng chọn diễn đàn", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (!ValidateInput(ref errText))
                {
                    MessageBoxEx.Show(errText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                UpdateMode = EnumUpdateMode.UPDATE;
                // Insert DienDan
                var objDienDanBus = new DienDanBUS(GlobalVariables.g_strPath);
                var objDienDanDto = new DienDanDTO
                {
                    ID = SelectedDienDan,
                    URL = txtLinkDienDan.Text.Trim(),
                    TenDangNhap = txtTenDangNhap.Text.Trim(),
                    MatKhau = txtMatKhau.Text.Trim()
                };
                if (objDienDanBus.Update(objDienDanDto))
                {
                    // Select max id -> that mean select id of DienDan just inserted
                    objDienDanBus = new DienDanBUS(GlobalVariables.g_strPath);
                    // Loop for list of Box
                    foreach (DataGridViewRow row in dtgvBoxLinks.Rows)
                    {
                        if (row.Cells["ID"].Value.ToString() == string.Empty)
                        {
                            if (row.Cells["URL"].Value.ToString().Trim() != string.Empty)
                            {
                                var objBoxBux = new BoxBUS(GlobalVariables.g_strPath);
                                var objBoxDto = new BoxDTO
                                {
                                    IDDienDan = SelectedDienDan,
                                    IDDanhMuc = int.Parse(row.Cells["IDDanhMuc"].Value.ToString()),
                                    URL = row.Cells["URL"].Value.ToString().Trim()
                                };
                                if (objBoxBux.Insert(objBoxDto))
                                {
                                    objBoxBux = new BoxBUS(GlobalVariables.g_strPath);
                                    var maxID = objBoxBux.RetrieveMaxID().Tables[0].Rows[0][0].ToString(); ;
                                    row.Cells["ID"].Value = maxID;
                                }
                            }
                        }
                        else
                        {
                            if (row.Cells["URL"].Value.ToString().Trim() == string.Empty)
                            {
                                var objBoxBus = new BoxBUS(GlobalVariables.g_strPath);
                                objBoxBus.Delete(int.Parse(row.Cells["ID"].Value.ToString()));
                                row.Cells["ID"].Value = string.Empty;
                            }
                            else
                            {
                                var objBoxBux = new BoxBUS(GlobalVariables.g_strPath);
                                var objBoxDto = new BoxDTO
                                {
                                    ID = int.Parse(row.Cells["ID"].Value.ToString()),
                                    URL = row.Cells["URL"].Value.ToString().Trim()
                                };
                                objBoxBux.Update(objBoxDto);
                            }
                        }
                    }
                    RefreshLinkDienDan();
                    MessageBoxEx.Show("Cập nhật thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                UpdateMode = EnumUpdateMode.NONE;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex.InnerException);
            }
        }


        public void RefreshLinkDienDan()
        {
            switch(UpdateMode)
            {
                case EnumUpdateMode.UPDATE:
                    foreach (DataGridViewRow row in dtgvDanhSachDienDan.Rows)
                    {
                        if (int.Parse(row.Cells["ID"].Value.ToString()) == SelectedDienDan)
                        {
                            row.Cells["URL"].Value = txtLinkDienDan.Text.Trim();
                        }
                    }
                    break;
                case EnumUpdateMode.DELETE:
                    foreach (DataGridViewRow row in dtgvDanhSachDienDan.Rows)
                    {
                        if (int.Parse(row.Cells["ID"].Value.ToString()) == SelectedDienDan)
                        {
                            dtgvDanhSachDienDan.Rows.Remove(row);
                        }
                    }
                    break;
            }
        }

        public List<DataGridViewRow> GetSelectedDienDan()
        {
            var lst = new List<DataGridViewRow>();
            foreach (DataGridViewRow row in dtgvDanhSachDienDan.Rows)
            {
                if (row.Selected)
                {
                    lst.Add(row);
                }
            }
            return lst;
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            var lst = GetSelectedDienDan();
            if (lst.Count == 0)
            {
                MessageBoxEx.Show("Vui lòng chọn diễn đàn", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (MessageBoxEx.Show("Bạn có chắc chắn xóa diễn đàn này không?", "Xóa", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {

                // Show waiting form
                GlobalVariables.PreLoading();
                //------- E ---------

                UpdateMode = EnumUpdateMode.DELETE;

                foreach (DataGridViewRow row in lst)
                {
                    var objBus = new DienDanBUS(GlobalVariables.g_strPath);

                    if (objBus.Delete(int.Parse(row.Cells["ID"].Value.ToString())))
                    {
                        // Remove boxlink belong to diendan
                        var objBoxBus = new BoxBUS(GlobalVariables.g_strPath);
                        objBoxBus.DeleteByIDDienDan(int.Parse(row.Cells["ID"].Value.ToString()));
                    }
                }

                LoadDanhSachDienDan();
                ResetForm();

                // Show waiting form
                GlobalVariables.PosLoading();
                //------- E ---------

                MessageBoxEx.Show("Xóa thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                UpdateMode = EnumUpdateMode.NONE;
            }
        }

        private void btnThemTuDong_Click(object sender, EventArgs e)
        {
            OpenFileDialog openDlg = new OpenFileDialog();

            openDlg.Title = "Lua chon file import";
            openDlg.Filter = "Executable file (*.txt)|*.txt";
            openDlg.RestoreDirectory = true;
            openDlg.InitialDirectory = Application.StartupPath + "\\Imports";

            if (openDlg.ShowDialog() == DialogResult.OK)
            {
                FileName = openDlg.FileName;

                FrmNhapTaiKhoan frm = new FrmNhapTaiKhoan();
                frm.Handler += ThemTuDong;
                frm.ShowDialog();
            }
        }

        private void ThemTuDong(object sender, EventArgs e)
        {
            var eventType = (TransferDataEvent)e;
            string[] comp = eventType.Data.Split(new char[] { '#' });

            var tendangnhap = comp[0];
            var matkhau = comp[1];

            // Show waiting form
            GlobalVariables.PreLoading();
            //------- E ---------

            try
            {
                using (StreamReader sr = new StreamReader(FileName))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        if (CheckingDienDanIsValid(line.Trim()) && !CheckingDienDanIsExist(line.Trim()))
                        {
                            var objDienDanBus = new DienDanBUS(GlobalVariables.g_strPath);
                            var objDienDanDto = new DienDanDTO
                            {
                                TenDangNhap = tendangnhap,
                                MatKhau = matkhau,
                                URL = line.Trim()
                            };
                            objDienDanBus.Insert(objDienDanDto);
                        } 
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex.InnerException);
            }

            LoadDanhSachDienDan();

            // Show waiting form
            GlobalVariables.PosLoading();
            //------- E ---------

            MessageBoxEx.Show("Thêm dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}
